package com.martini.controller;

import com.martini.model.R;
import com.martini.request.UrlShortenReq;
import com.martini.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.RandomAccessFile;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author whxiang at 2021/8/30 23:50
 */
@RestController
@RequestMapping("/shorten")
@Slf4j
public class ShortenerController {

    @Resource
    private CacheService cacheService;

    @Resource(name = "myRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("")
    public R shorten(@RequestBody UrlShortenReq shortenReq) {
        log.info("shorten request is: [{}]", shortenReq);
        Assert.notNull(shortenReq.getUrl(), "url is null");
        Assert.notNull(shortenReq.getExpire(), "expire is null");
        String uuid = UUID.randomUUID().toString().substring(0, 8);
        redisTemplate.opsForValue().set(uuid, shortenReq.getUrl(), 1800, TimeUnit.SECONDS);
        Map<String, Object> data = new HashMap<>();
        data.put("origin", shortenReq.getUrl());
        data.put("time", new Date());
        data.put("token", uuid);
        return R.success().setData(data);
    }

    @GetMapping("/{token}")
    public R getOriginUrl(@PathVariable("token") String token) {
        return R.success().setData(redisTemplate.opsForValue().get(token));
    }
}
